package com.gin.no_gay_alliance.adpter;

import android.app.DownloadManager;
import android.content.Context;
import android.content.DialogInterface;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.CompoundButton;
import android.widget.ImageView;

import androidx.annotation.NonNull;
import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.fragment.app.FragmentActivity;

import com.gin.jackson.utils.ObjectUtils;
import com.gin.nga.response.field.Attachment;
import com.gin.no_gay_alliance.R;
import com.gin.no_gay_alliance.adpter.base.BaseBindingRecyclerViewAdapter;
import com.gin.no_gay_alliance.databinding.ItemAttachmentBinding;
import com.gin.no_gay_alliance.exception.RequireParamException;
import com.gin.no_gay_alliance.utils.AlertDialogUtils;
import com.gin.no_gay_alliance.utils.ImageUtils;
import com.gin.no_gay_alliance.viewmodel.AttachmentModel;

import java.util.List;
import java.util.Locale;
import java.util.stream.Collectors;

/**
 * 附件列表
 *
 * @author : ginstone
 * @version : v1.0.0
 * @since : 2023/9/3 15:23
 **/
public class AttachmentItemAdapter extends BaseBindingRecyclerViewAdapter<ItemAttachmentBinding, AttachmentModel> implements View.OnLongClickListener, View.OnClickListener, CompoundButton.OnCheckedChangeListener {
    public static final String TAG = AttachmentItemAdapter.class.getSimpleName();

    public AttachmentItemAdapter(Context context) {
        super(context);
    }

    public AttachmentItemAdapter(@NonNull Context context, @NonNull List<AttachmentModel> data) {
        super(context, data);
    }

    @Override
    protected void onBindViewHolder(ViewHolder<ItemAttachmentBinding> holder, @NonNull ItemAttachmentBinding b, int position, AttachmentModel item) {
        // 加载最小缩略图
        configAttachmentThumb(item.extension, b.ivAvatar, iv -> ImageUtils.loadAttachment(context, Attachment.PREFIX + findUrl(item), b.ivAvatar));
        b.tvFilename.setText(item.getDisplayName());
        b.tvSize.setText(String.format(Locale.CHINA, "%d KB", item.size));
        b.tvType.setText(item.type);
        // 复选框
        b.cbDownload.setTag(item);
        b.cbDownload.setChecked(item.checked);
        b.cbDownload.setOnCheckedChangeListener(this);

        // 头像
        b.ivAvatar.setTag(item);
        b.ivAvatar.setOnClickListener(this);

        b.getRoot().setTag(b.ivAvatar);
        b.getRoot().setOnClickListener(this);
        b.getRoot().setOnLongClickListener(this);
    }

    @NonNull
    @Override
    protected ItemAttachmentBinding buildBinding(LayoutInflater inflater) {
        return ItemAttachmentBinding.inflate(inflater);
    }

    @Override
    public boolean onLongClick(View v) {
        ImageView iv = (ImageView) v.getTag();
        AttachmentModel item = (AttachmentModel) iv.getTag();
        DownloadManager downloadManager = (DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE);
        String message = String.format(Locale.CHINA, "即将保存附件: %s", item.getDisplayName());

        AlertDialogUtils.showConfirm(context, "保存附件", message, (dialog, which) -> {
            if (which == DialogInterface.BUTTON_POSITIVE) {
                downloadManager.enqueue(item.buildDownloadRequest());
            }
        });

        return true;
    }

    @Override
    public void onClick(View v) {
        // 点击根节点时间接触发预览
        if (v instanceof ConstraintLayout) {
            ImageView iv = (ImageView) v.getTag();
            AttachmentModel item = (AttachmentModel) iv.getTag();
            preview(iv, item);
        }
        // 预览功能
        if (v.getId() == R.id.iv_avatar && v instanceof ImageView) {
            AttachmentModel item = (AttachmentModel) v.getTag();
            // 可以预览的附件列表
            preview((ImageView) v, item);
        }
    }

    @Override
    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
        AttachmentModel item = (AttachmentModel) buttonView.getTag();
        item.checked = isChecked;
    }

    private void preview(ImageView iv, AttachmentModel item) {
        List<AttachmentModel> imgList = data.stream().filter(i -> "img".equals(i.type)).collect(Collectors.toList());
        int position = imgList.indexOf(item);
        if (position == -1) {
            handler.toast("仅支持预览图片");
            return;
        }
        // 预览图片
        ImageUtils.preview((FragmentActivity) context, imgList, position, iv);
    }

    public static void configAttachmentThumb(String extension, ImageView iv, Handler handler) {
        if (ObjectUtils.isEmpty(extension)) {
            throw new RequireParamException();
        }
        switch (extension) {
            case "mp3":
                iv.setImageResource(R.drawable.ic_audio_24);
                break;
            case "mp4":
                iv.setImageResource(R.drawable.ic_video_24);
                break;
            case "zip":
                iv.setImageResource(R.drawable.ic_zip);
                break;
            default: {
                if (handler != null) {
                    handler.handle(iv);
                }
            }
        }
    }

    public static String findUrl(AttachmentModel item) {
        if (!ObjectUtils.isEmpty(item.thumbUrls)) {
            return item.thumbUrls.get(0);
        }
        return item.url;
    }

    public interface Handler {
        void handle(ImageView iv);
    }
}
